﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;
using System.Runtime.Serialization;
using System.Threading;
using Microsoft.WindowsMobile.PocketOutlook;
using OCDStudio.SMSPPP.WindowsMobile.Server.SMSPPPDataSetTableAdapters;



namespace OCDStudio.SMSPPP.WindowsMobile.Server
{
    class SMSPPPMobileServer
    {
        private int networkPort;
        private SENT_SMSTableAdapter smsLog;
        private List<Thread> clients = new List<Thread>();
        private bool started = false;
        private OutlookSession session;
        private TcpListener listener;

        #region "Properties"

        public int NetworkPort
        {
            get { return networkPort; }
            set { networkPort = value; }
        }

        public SENT_SMSTableAdapter SmsLog
        {
            get { return smsLog; }
            set { smsLog = value; }
        }

        public OutlookSession Session
        {
            get { return session; }
            set { session = value; }
        }

        public TcpListener Listener
        {
            get { return listener; }
            set { listener = value; }
        }

        #endregion

        
        

        public SMSPPPMobileServer(int port)
        {            
            this.networkPort = port;
            this.session = new OutlookSession();
            this.smsLog = new SENT_SMSTableAdapter();
        }


        public void StartServer() {
            if (started) return;
            
            listener = new TcpListener(networkPort);
            listener.Start();

            while (true)
            {
                try
                {
                    TcpClient cl = listener.AcceptTcpClient();
                    SMSPPPClientHandler handler = new SMSPPPClientHandler(this, cl);
                    Thread t = new Thread(new ThreadStart(handler.ManageTcpClient));
                    clients.Add(t);
                    t.Start();
                }
                catch (ThreadAbortException) {
                    listener.Stop();
                    break;
                }
                
            }

        }

        public void StopServer() {
            foreach (Thread t in clients) {
                t.Abort();
            }
            listener.Stop();            
        }

        
    }
}
